package cn.ctyun.xstore.s3.api.object;

import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;

import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class MultipleUpload {

    public static String init(String bucket, String key, AmazonS3 s3) {
        InitiateMultipartUploadRequest req = new InitiateMultipartUploadRequest(bucket, key);
        InitiateMultipartUploadResult res = s3.initiateMultipartUpload(req);
        return res.getUploadId();
    }

    public static List<String> getUploadPartUrls(String bucket, String key, String uploadId, int totalParts, AmazonS3 s3) {
        List<String> urls = new ArrayList<>(totalParts);
        for (int i = 1; i <= totalParts; i++) {
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket,
                    key, HttpMethod.PUT);
            request.addRequestParameter("partNumber", Integer.toString(i));
            request.addRequestParameter("uploadId", uploadId);
            request.setExpiration(getOneDayExpire());
            URL url = s3.generatePresignedUrl(request);
            urls.add(url.toString());
        }
        return urls;
    }

    private static Date getOneDayExpire() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        return calendar.getTime();
    }

    public static void complete(String bucket, String key, String uploadId, List<PartETag> eTags, AmazonS3 s3) {

        CompleteMultipartUploadRequest req = new CompleteMultipartUploadRequest(bucket, key, uploadId, eTags);
        s3.completeMultipartUpload(req);

    }

    public static void abort(String bucket, String key, String uploadId, AmazonS3 s3) {
        AbortMultipartUploadRequest req = new AbortMultipartUploadRequest(bucket, key, uploadId);
        s3.abortMultipartUpload(req);
    }

}
